package com.tzx.fluttermixedapplication.activity

import android.os.Bundle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import coil.load
import com.tzx.base.base.BaseActivity
import com.tzx.base.utils.createViewModels
import com.tzx.fluttermixedapplication.databinding.ActivityViewModelTestLayoutBinding
import com.tzx.fluttermixedapplication.viewmodel.WeatherViewModel
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
import kotlinx.coroutines.withContext

class ViewModelTestActivity : BaseActivity() {
    private val viewModel: WeatherViewModel by createViewModels { this }
    private val binding: ActivityViewModelTestLayoutBinding by lazy {
        ActivityViewModelTestLayoutBinding.inflate(
            layoutInflater
        )
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        viewModel.getWeatherWithCityData("北京")
        viewModel.getOneDayEnglish()
        lifecycleScope.launch(SupervisorJob()) {
            repeatOnLifecycle(Lifecycle.State.CREATED) {
                viewModel.weatherFlow.collectLatest { data ->
                    data.let {
                        binding.textView.text = data
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.CREATED) {
                viewModel.oneDayEnglishDataFlow.collectLatest {
                    binding.textView2.text = it.content
                    binding.imageView.load(it.img)
                }
            }
        }
    }

}